import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AdminProfile {
  id: number;
  username: string;
  email: string;
  is_active: boolean;
  last_login: string;
}

interface AuthState {
  token: string | null;
  admin: AdminProfile | null;
  isAuthenticated: boolean;
  login: (token: string, admin: AdminProfile) => void;
  logout: () => void;
  updateAdmin: (admin: AdminProfile) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    set => ({
      token: null,
      admin: null,
      isAuthenticated: false,
      login: (token, admin) =>
        set({
          token,
          admin,
          isAuthenticated: true,
        }),
      logout: () =>
        set({
          token: null,
          admin: null,
          isAuthenticated: false,
        }),
      updateAdmin: admin =>
        set(state => ({
          admin,
          isAuthenticated: state.token !== null,
        })),
    }),
    {
      name: 'digital-me-auth',
    }
  )
);
